package org.common.utils.tool.window;

import java.awt.*;
import java.util.Collections;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 组件工具
 * @author zhouzhibing
 * @date 2025/1/7
 */
public class ComponentTool {

    /**
     * 获取指定容器下所有组件
     * @param container 容器对象
     * @return 返回组件列表<组件类型, <组件名称 ,组件对象>>
     */
    public static Map<Class<?> , Map<String , Component>> getComponents(Container container) {
        ConcurrentHashMap<Class<?> , ConcurrentHashMap<String , Component>> map = new ConcurrentHashMap<>();
        addComponent(map , container);

        for (Component c : container.getComponents()) {
            addComponent(map , c);

            if (c instanceof Container) {
                Map<Class<?> , Map<String , Component>> innerMap = getComponents((Container) c);
                for (Map.Entry<Class<?>, Map<String, Component>> entry : innerMap.entrySet()) {
                    ConcurrentHashMap<String, Component> innerComponentMap = map.computeIfAbsent(entry.getKey(), (o) -> new ConcurrentHashMap<>());
                    innerComponentMap.putAll(entry.getValue());
                }
            }
        }
        return Collections.unmodifiableMap(map);
    }

    /**
     * 在对应map中添加组件
     * @param map 组件列表
     * @param c 组件对象
     */
    private static void addComponent(ConcurrentHashMap<Class<?> , ConcurrentHashMap<String , Component>> map , Component c) {
        String name = c.getName();
        if(name == null || name.isEmpty()) {
            name = UUID.randomUUID().toString();
        }
        ConcurrentHashMap<String, Component> componentMap = map.computeIfAbsent(c.getClass(), (o) -> new ConcurrentHashMap<>());
        componentMap.put(name , c);
    }
}
